package com.hongkuncheng.cms.controller.admin;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.HttpHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Leavemessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 留言管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/leavemessage")
public class AleavemessageController extends BaseController {

    // 留言列表
    @RequestMapping
    public String index() {
        Criteria criteriaLeavemessage = factorySession.createCriteria(Leavemessage.class);
        StringBuilder callbackparams = new StringBuilder();
        int state = request.getParameter("state") == null ? -1 : Integer.parseInt(request.getParameter("state"));
        if (state > -1) {
            criteriaLeavemessage.add(Restrictions.eq("checked", (state == 1)));
            callbackparams.append("&state=" + state);
        }
        request.setAttribute("state", state);
        String keywords = request.getParameter("keywords") == null ? "" : request.getParameter("keywords");
        if (!keywords.isEmpty()) {
            criteriaLeavemessage.add(Restrictions.like("contents", keywords, MatchMode.ANYWHERE));
            callbackparams.append("&keywords=" + keywords);
        }
        request.setAttribute("keywords", keywords);
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<Leavemessage> leavemessages = criteriaLeavemessage.addOrder(Order.asc("checked"))
                .addOrder(Order.desc("subtime")).setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize)
                .list();
        request.setAttribute("leavemessages", leavemessages);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = leavemessages.size() == 0 ? 0 :
                Integer.parseInt(criteriaLeavemessage.setProjection(Projections.countDistinct("id"))
                        .setFirstResult(0).uniqueResult().toString());
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        return view();
    }

    // 留言详细
    @RequestMapping("detail")
    public String detail() {
        int leavemessageId = Integer.parseInt(request.getParameter("leavemessageid"));
        Leavemessage leavemessage = factorySession.get(Leavemessage.class, leavemessageId);
        request.setAttribute("leavemessage", leavemessage);
        request.setAttribute("callbackparams", request.getParameter("callbackparams"));
        return view();
    }

    // 审核通过
    @RequestMapping("checkpass")
    @ResponseBody
    public void checkpass() {
        checkAdminPermission("office_leavemessage_manage");
        int leavemessageId = Integer.parseInt(request.getParameter("leavemessageid"));
        Leavemessage leavemessage = factorySession.load(Leavemessage.class, leavemessageId, LockMode.PESSIMISTIC_WRITE);
        leavemessage.setChecked(true);
        recordLog("审核留言《" + StringHelper.substring(leavemessage.getContents(), 20) + "》通过");
        PageHelper.confirmAndRedirect("审核成功，是否更新相关静态页面？", "./createpage", "./?" +
                request.getParameter("callbackparams"));
    }

    // 生成静态页面
    @RequestMapping("createpage")
    @ResponseBody
    public void createpage() {
        String filecontent = HttpHelper.get("http://localhost:" + serverPort + "/frontpage/leavemessage");
        FileHelper.write(applicationDirectory + "/leavemessage/index.html", filecontent);
        PageHelper.alertAndRedirect("相关静态页面更新成功", "./?" + request.getParameter("callbackparams"));
    }

    // 留言删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("office_leavemessage_manage");
        String[] leavemessageIds = request.getParameter("leavemessageids").split(",");
        List<Leavemessage> leavemessages = factorySession.createCriteria(Leavemessage.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(leavemessageIds)))
                .setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Leavemessage leavemessage : leavemessages) factorySession.delete(leavemessage);
        recordLog("删除《" + StringHelper.substring(leavemessages.get(0).getContents(), 20) + "》等" +
                leavemessageIds.length + "条留言");
        PageHelper.alertAndRedirect("删除成功", "./?" + request.getParameter("callbackparams"));
    }

}
